class WebSocketService {
    constructor() {
        this.socket = null;
        this.isConnected = false;
        this.reconnectTimer = null;
        this.reconnectInterval = 3000; //重连时间间隔，单位为毫秒
        this.eventListeners = new Map(); // 存储事件监听器
    }

    // 连接WebSocket
    connect(url) {
        // 关闭现有连接
        if (this.socket) {
            this.socket.close();
        }

        try {
            this.socket = new WebSocket(url);

            // 连接成功
            this.socket.onopen = () => {
                console.log("WebSocket连接成功");
                this.isConnected = true;
                this.clearReconnectTimer();
                this.emit("connect", true);
            };

            // 接收消息
            this.socket.onmessage = (event) => {
                try {
                    const message = JSON.parse(event.data);
                    console.log("收到消息:", message);
                    this.handleMessage(message);
                } catch (error) {
                    console.error("解析WebSocket消息失败:", error);
                }
            };

            // 连接关闭
            this.socket.onclose = (event) => {
                console.log("WebSocket连接关闭，代码:", event.code);
                this.isConnected = false;
                this.emit("disconnect", event);
                this.startReconnect(url);
            };

            // 连接错误
            this.socket.onerror = (error) => {
                console.error("WebSocket错误:", error);
                this.isConnected = false;
                this.emit("error", error);
                this.startReconnect(url);
            };
        } catch (error) {
            console.error("创建WebSocket连接失败:", error);
            this.startReconnect(url);
        }
    }

    // 处理接收到的消息
    handleMessage(message) {
        if (message.type && this.eventListeners.has(message.type)) {
            // 触发对应类型的事件
            this.eventListeners.get(message.type).forEach((callback) => {
                callback(message.data);
            });
        } else {
            // 触发全局消息事件
            this.emit("message", message);
        }
    }

    // 发送消息
    send(data) {
        if (!this.isConnected || !this.socket) {
            console.error("WebSocket未连接，无法发送消息");
            return false;
        }

        try {
            this.socket.send(JSON.stringify(data));
            return true;
        } catch (error) {
            console.error("发送消息失败:", error);
            return false;
        }
    }

    // 关闭连接
    close() {
        if (this.socket) {
            this.socket.close();
            this.socket = null;
            this.isConnected = false;
            this.clearReconnectTimer();
        }
    }

    // 开始重连
    startReconnect(url) {
        this.clearReconnectTimer();
        this.reconnectTimer = setTimeout(() => {
            console.log("尝试重新连接WebSocket...");
            this.connect(url);
        }, this.reconnectInterval);
    }

    // 清除重连定时器
    clearReconnectTimer() {
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
            this.reconnectTimer = null;
        }
    }

    // 注册事件监听
    on(eventType, callback) {
        if (!this.eventListeners.has(eventType)) {
            this.eventListeners.set(eventType, []);
        }
        this.eventListeners.get(eventType).push(callback);
    }

    // 移除事件监听
    off(eventType, callback) {
        if (this.eventListeners.has(eventType)) {
            if (callback) {
                this.eventListeners.set(
                    eventType,
                    this.eventListeners
                        .get(eventType)
                        .filter((cb) => cb !== callback)
                );
            } else {
                this.eventListeners.delete(eventType);
            }
        }
    }

    // 触发事件
    emit(eventType, data) {
        if (this.eventListeners.has(eventType)) {
            this.eventListeners.get(eventType).forEach((callback) => {
                callback(data);
            });
        }
    }

    // 检查连接状态
    isConnected() {
        return this.isConnected;
    }
}

// 创建单例实例
export const webSocketService = new WebSocketService();
